package edu.gdpu.memory.direct;

import sun.misc.Unsafe;

import java.lang.reflect.Field;

/**
 * @author mazebin
 * @date 2021年 07月15日 16:13:07
 * 直接内存分配的底层原理：Unsafe
 * ByteBuffer 的实现类内部，使用了 Cleaner （虚引用）来监ByteBuffer 对象，一旦ByteBuffer 对象被垃圾回收，
 * 那么就会由 ReferenceHandler 线程通过 Cleaner 的 clean 方法调用DirectByteBUffer.Deallocator.run方法调用unsafe freeMemory 来释放直接内存
 */
public class DirectMemoryTest4 {
    static  final  int _1GB=1024*1024*1024;
    public static void main(String[] args) {
        try {
            Unsafe unsafe = getUnsafe();
            //分配内存(还没真正分配)
            long l = unsafe.allocateMemory(_1GB);
            //真正分配内存
            unsafe.setMemory(l,_1GB,(byte)0);
            System.in.read();
            //释放内存
            unsafe.freeMemory(l);
            System.in.read();
        } catch ( Exception e ) {
            e.printStackTrace();
        }
    }

    private static Unsafe getUnsafe() throws Exception {
        Field theUnsafe = Unsafe.class.getDeclaredField("theUnsafe");
        theUnsafe.setAccessible(true);
       Unsafe o = (Unsafe) theUnsafe.get(null);
return o;

    }
}
